<template>
<div class="myAddress">
  <y-table
    ref="table"
    border
    :getDataWay="{
      data: tableData
    }"
    :columns="columns"
  >
    <template slot="button">
      <el-button type="primary" @click="addAddress">添加地址</el-button>
    </template>
    <el-table-column slot="sendStatus" label="默认发货地址" align="center" header-align="center" width="110">
      <template v-slot="scope">
        <el-popconfirm
          :title="scope.row.sendStatus === 0 ? '是否设为默认发货地址？' : '是否解除默认发货地址？'"
          @confirm="changeStatus(scope.row, 'sendStatus')"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="scope.row.sendStatus"
            :active-value="1"
            :inactive-value="0"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="receiveStatus" label="默认收货地址" align="center" header-align="center" width="110">
      <template v-slot="scope">
        <el-popconfirm
            :title="scope.row.receiveStatus === 0 ? '是否设为默认收货地址？' : '是否解除默认收货地址？'"
            @confirm="changeStatus(scope.row, 'receiveStatus')"
        >
          <el-switch
              disabled
              slot="reference"
              v-model="scope.row.receiveStatus"
              :active-value="1"
              :inactive-value="0"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="140">
      <template v-slot="scope">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editAddress(scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除该地址？"
            @confirm="delAddress(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    width="50%"
    :formAttrs="forms.formAttrs"
    :columns="forms.formColumns"
    @ensure="ensureModel">
    <template slot="province">
      <y-address-selector
        v-model="provinceVal"></y-address-selector>
    </template>
    <template slot="label">
      <el-checkbox-group v-model="labelVal">
        <el-checkbox
          v-for="item in (labelOptions || [])"
          :key="item.code"
          :label="item.code">{{item.dictName}}</el-checkbox>
      </el-checkbox-group>
    </template>
  </y-form>
</div>
</template>

<script>
export default {
  name: "myAddress",
  inject: ['getDict', 'pattern'],
  computed:{
    provinceVal:{
      get(){
        if(!(this.forms.formModel.province && this.forms.formModel.city && this.forms.formModel.region)){
          return '';
        }
        return [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region];
      },
      set(val){
        if(!val || !val.length){
          [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region] = ['','',''];
        }else{
          [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region] = val;
        }
      }
    },
    labelVal:{
      get(){
        return this.forms.formModel.label.trim() ? this.forms.formModel.label.trim().split(',') : [];
      },
      set(val = ''){
        this.forms.formModel.label = val.toString();
      }
    }
  },
  asyncComputed:{
    async labelOptions(){
      return this.getDict('address_code');
    }
  },
  data(){
    return{
      address: "",
      tableData: [],
      columns: [{
        label: "收/发货人姓名",
        prop: "name",
        width: '115'
      },{
        label: "收/发货人电话",
        prop: "phone",
        width: '115'
      },{
        label: "省/市/区(县)",
        prop: "province",
        formatter(row){
          if(!row.province) return '';
          return [row.province, row.city, row.region].toString();
        }
      },{
        label: "详细地址",
        prop: "detailAddress"
      },{
        label: "邮编",
        prop: "postCode",
        width: '80'
      },{
        label: "标签",
        prop: "label",
        width: '80',
        formatter: (function(row){
          return this.$$getArrayName(row.label, this.labelOptions);
        }).bind(this)
      },
      {
        label: "默认发货地址",
        prop: "sendStatus",
        template: true
      },
      {
        label: "默认收获地址",
        prop: "receiveStatus",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加地址',
          'EDIT': '编辑地址'
        },
        currentForm: null,
        formModel: {
          id: '',
          name: '',
          phone: '',
          province: '',
          city: '',
          region: '',
          detailAddress: '',
          postCode: '',
          label: '',
          sendStatus: 0,
          receiveStatus: 0
        },
        showForm: false,
        formAttrs:{
          labelWidth: '125px',
          rules: {
            name: [{required: true, message: "请输入个人姓名", trigger: "blur"}],
            phone: [{required: true, message: "请输入联系电话", trigger: "blur"}],
            province: [{required: true, message: "请选择省/市/区(县)", trigger: "change"}],
            detailAddress: [{required: true, message: "请输入详细地址", trigger: "blur"}],
            postCode: [
              {required: true, message: "请输入邮编", trigger: "blur"},
              {pattern: this.pattern.postCode, message: "邮编格式不正确", trigger: "blur"}
            ]
          }
        },
        formColumns:[
          {
            label: "收/发货人姓名",
            prop: "name",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 10,
                showWordLimit: true
              }
            }
          },
          {
            label: "收/发货人电话",
            prop: "phone",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 15,
                showWordLimit: true
              }
            }
          },
          {
            label: "省/市/区（县）",
            prop: "province",
            template: true
          },
          {
            label: "详细地址",
            prop: "detailAddress",
            comp:{
              compType: 'input',
              attrs:{
                type: 'textarea',
                maxlength: 50,
                showWordLimit: true,
                autosize: {
                  minRows: 3
                }
              }
            }
          },
          {
            label: "邮编",
            prop: "postCode",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 6,
                showWordLimit: true
              }
            }
          },
          {
            label: "标签",
            prop: "label",
            template: true,
          }
        ],
      }
    }
  },
  created(){ this.loadData() },
  methods:{
    loadData(){
      this.$yAxios({
        url: this.$api.self.queryAddress,
        data: {},
        loading: true,
      }, info => {
        this.tableData = info;
      })
    },
    resetForm(data = this.forms.currentForm){
      this.forms.formModel = Object.assign({
        id: '',
        name: '',
        phone: '',
        province: '',
        city: '',
        region: '',
        detailAddress: '',
        postCode: '',
        label: '',
        sendStatus: 0,
        receiveStatus: 0
      }, data || {})
    },
    addAddress(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editAddress(data){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = data;
      this.resetForm();
      this.forms.showForm = true;
    },
    delAddress(data){
      this.$yAxios({
        url: this.$api.self.delAddress,
        data:{
          id: data.id
        },
        loading: true
      }, info => {
        this.loadData();
      })
    },
    ensureModel(form){
      let newForm, url;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
        url = this.$api.self.updateAddress;
      }else{
        newForm = Object.assign({}, form);
        url = this.$api.self.addAddress
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.loadData();
      })
    },
    changeStatus(data, key){
      this.$yAxios({
        url: this.$api.goods.resetClassifyStatus,
        data:{
          id: data.id,
          [key]: data[key] ^ 1
        },
        loading: true
      }, info => {
        this.loadData();
      })
    }
  }
}
</script>

<style scoped lang="less">
.myAddress{
  margin-top: -20px;
}
</style>